//导购链接
(function() {
	var config = require("../_include/config");
	var db = require("../db/index");
	var md5 = require("../_include/md5");
	var helper = require("../_include/helper");
	var db_table_name = config.dbname.busGuide;
	var db_id_prefix = config.dbIdPrefix.busGuide;
	var UserCon = require("../user/_con");
	//构造函数
	var _con = function(info) {
		if (!info) {
			throwCusError("参数错误，导购信息不可为空");
		}
		var self = this;
		self._id = db_id_prefix + info.bus_id + "|" + info.user_id
		if (!info.user_id) {
			throwCusError("参数错误，导购链接中用户ID不可为空")
		}
		if (!UserCon.get(info.user_id)) {
			throwCusError("找不到指定用户")
		}
		self.bus_id = info.bus_id;
		self.user_id = info.user_id;

		self.achs = [];

		//历史积累的总份额
		self.total_acc = 0;

		//累积的份额，可兑换的
		self.acc = 0;

		//申请的兑换现金的份额，如果为空则不在兑换状态，不为空则可以发起申请
		self.apply_acc = 0;

		self.state = _con.STATE.未申请兑换;

		db.insert(db_table_name, self);
		console.log("注册了一个商家：", info.name);
	};

	module.exports = _con;

	//技能
	_con.prototype = require("./skill");

	_con.STATE = {
		"未申请兑换": 0,
		"申请兑换中": 1,
		"商家已经付款": 2,
		"用户确认收款": 3 //total_acc+apply_acc && state = 未申请兑换
	};

	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		if (result) {
			result.__proto__ = _con.prototype;
		}
		return result;
	};
	//获取或直接生成一个对象
	_con.build = function(info) {
		var _id = db_id_prefix + info.bus_id + "|" + info.user_id;
		var instance = _con.get(_id);
		//如果没有相应的对象，直接生成
		if (!instance) {
			instance = new _con(info);
		}
		console.log("--------------------------");
		console.log(instance);
		console.log("--------------------------");
		return instance._id;
	};
	//通过商家名查找
	_con.findByBusId = function(bus_id) {
		// var key = db_id_prefix+bus_id+"|";
		return db.find_list(db_table_name, {
				bus_id: bus_id
			})
			/*.map(function(instance) {
							return instance.__proto__ = _con.prototype;
						})*/
		;
	};
	//通过用户名查找
	_con.findByUserId = function(user_id) {
		return db.find_list(db_table_name, {
			user_id: user_id
		});
	};

}());